package com.td.core.communication;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

public class Reciever extends Thread {

	private Socket socket;
	private ObjectInputStream input;
	
	private MainReciever mr;
	
	public Reciever(Socket s, MainReciever mr) throws IOException {
		socket = s;
		if(s != null ) {
			input = new ObjectInputStream(socket.getInputStream());
			this.mr = mr;
		}
	}
	
	public void run() {
		while(!interrupted()) {
			Sendable<?> obj = null;
			try {
				obj = (Sendable<?>) input.readObject();
			} catch (IOException e) {
				obj = null;
			} catch (ClassNotFoundException e) {
				throw new RuntimeException(e);
			}
			
			if(obj != null) {
				mr.recieve(obj);
			}
			
			try {
				sleep(10);
			} catch (InterruptedException e) {
				this.interrupt();
			}
		}
		try {
			input.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			input = null;
			socket = null;
		}
	}
}
